package com.trainfinder.proxy;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

public abstract class AbstractProxy {
	 
	public void start() {

		Logger logger;

		int localPortIndex = 0;
		while (true) 
		{
			logger = new NullLoggerImpl();
			localPortIndex++;

			Service service;
			try {

		 		while (true) 
				{
					try {
						service = getService();
						break;
					} catch (ServerCreationException e) {
				//		e.printStackTrace();
					}
				}
				InputStream input = service.getInputStream();
				if (input == null) {
			 	  	break;
				}
				OutputStream output = service.getOutputStream();

				byte[] bytes = new byte[9024];
				try {
					while (true) {
						int count = input.read(bytes, 0, bytes.length);

						if (count == -1) {
							output.write(-1);
							output.flush();
							break;
						} else {
							output.write(bytes, 0, count);
							logger.log(PortType.Local, localPortIndex, bytes,
									count);

						}
						output.flush();
					}
				} catch (SocketException e) {
					// do nothing
				} catch (IOException r) {
					// do nothing
				}

			} catch (ServerCreationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}

	protected abstract Service getService() throws ServerCreationException;

}